package flexo.common;

import java.util.HashMap;

/**
 * Generic resource pool that gets track of duplicate resources.
 * @author Miguel
 */
public class ResourcePool
{
	protected HashMap<String, ReferenceCount> resourceList;
	
	public ResourcePool()
	{
		resourceList = new HashMap<String, ReferenceCount>();
	}
	
	/**
	 * @param resourceName The name of the resource you want to retrieve.
	 * @return the resource with that name, if exists.
	 */
	protected Object get(String resourceName)
	{
		return resourceList.get(resourceName);
	}
	
	/**
	 * Adds a resource to the pool. 
	 * @param resourceName The name of the resource.
	 * @param resource The resource itself.
	 */
	public void add(String resourceName, ReferenceCount resource)
	{
		resourceList.put(resourceName, resource);
	}
	
	/**
	 * Removes a specific resource from the pool.
	 * @param resourceName The name of the resource that will be deleted.
	 */
	public void remove(String resourceName)
	{
		resourceList.remove(resourceName);
	}
	
	/**
	 * Removes a specific resource from the pool.
	 * @param resourceName The resource that you want to delete.
	 */
	public void remove(ReferenceCount resource)
	{
		resourceList.values().remove(resource);
	}
	
	/**
	 * @return number of resources on the pool.
	 */
	public int getResourceCount()
	{
		return resourceList.size();
	}
	
	/**
	 * Clean objects with 0 references.
	 * Usually happens when you create a resource and you don't assign it to an entity.
	 */
	public void clean()
	{
		for (ReferenceCount r : resourceList.values())
		{
			r.clean();
		}
	}
}
